<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="车间编码" prop="workshopCode">
        <el-input
          v-model="queryParams.workshopCode"
          placeholder="请输入车间编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车间名称" prop="workshopName">
        <el-input
          v-model="queryParams.workshopName"
          placeholder="请输入车间名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['workshop:workshop:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['workshop:workshop:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['workshop:workshop:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['workshop:workshop:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="workshopList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="车间ID" align="center" prop="workshopId" /> -->
      <el-table-column label="车间编码" align="center" prop="workshopCode" />
      <el-table-column label="车间名称" align="center" prop="workshopName" />
      <el-table-column label="面积" align="center" prop="area" />
      <el-table-column label="负责人" align="center" prop="charge" />
      <el-table-column label="是否启用" align="center" prop="enableFlag" >
        <template #default="scope">
          <el-tag type="primary" v-if="scope.row.enableFlag ==='Y'">是</el-tag>
          <el-tag type="danger" v-else>否</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['workshop:workshop:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['workshop:workshop:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改车间对话框1 -->
 <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <!-- 表单区域 -->
      <el-form ref="workshopRef" :model="form" :rules="rules" size="medium" label-width="100px">
        <el-row gutter="15">
          <!-- 车间编码 + 自动生成开关（修复文字位置） -->
          <el-col :span="12">
            <el-form-item label="车间编码" prop="workshopCode">
              <el-input 
                v-model="form.workshopCode" 
                placeholder="请输入车间编码" 
                clearable
                :disabled="autoGenerateCode"  
                :style="{width: '80%'}"
              ></el-input>
              <!-- 自动生成文字移到开关后面 -->
              <el-switch 
                v-model="autoGenerateCode" 
                style="margin-left: 10px;"
                @change="handleCodeSwitchChange" 
              ></el-switch>
              <span style="margin-left: 5px;">自动生成</span>
            </el-form-item>
          </el-col>

          <!-- 车间名称 -->
          <el-col :span="24">
            <el-form-item label="车间名称" prop="workshopName">
              <el-input 
                v-model="form.workshopName" 
                placeholder="请输入车间名称" 
                clearable
                :style="{width: '100%'}"
              ></el-input>
            </el-form-item>
          </el-col>

          <!-- 面积 -->
          <el-col :span="12">
            <el-form-item label="面积" prop="area">
              <el-input-number 
                v-model="form.area" 
                placeholder="请输入面积" 
                :min="0" 
                :precision="2"  
                :style="{width: '100%'}"
              ></el-input-number>
            </el-form-item>
          </el-col>

          <!-- 负责人 -->
          <el-col :span="24">
            <el-form-item label="负责人" prop="charge">
              <el-input 
                v-model="form.charge" 
                placeholder="请输入负责人" 
                clearable
                :style="{width: '100%'}"
              ></el-input>
            </el-form-item>
          </el-col>

          <!-- 是否启用 -->
          <el-col :span="12">
            <el-form-item label="是否启用" prop="enableFlag">
              <el-radio-group v-model="form.enableFlag" size="medium">
                <el-radio label="Y">是</el-radio>
                <el-radio label="N">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <!-- 备注 -->
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input 
                v-model="form.remark" 
                type="textarea" 
                placeholder="请输入备注内容"
                :autosize="{minRows: 4, maxRows: 5}" 
                :style="{width: '100%'}"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 确定/取消按钮（修复显示问题：移到el-dialog直接子元素） -->
      <div  class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Workshop">
import { listWorkshop, getWorkshop, delWorkshop, addWorkshop, updateWorkshop } from "@/api/workshop/workshop"

// 新增：自动生成编码开关状态
const autoGenerateCode = ref(false)
const { proxy } = getCurrentInstance()

const workshopList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    workshopCode: null,
    workshopName: null,
  },
  rules: {
    workshopCode: [
      { required: true, message: "车间编码不能为空", trigger: "blur" }
    ],
    workshopName: [
      { required: true, message: "车间名称不能为空", trigger: "blur" }
    ],
    enableFlag: [
      { required: true, message: "是否启用不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)
// 监听自动生成开关状态，动态调整编码验证规则
watch(autoGenerateCode, (newVal) => {
  if (newVal) {
    // 开关打开：编码非必填（自动生成）
    rules.value.workshopCode = [{ required: false }]
    // 立即生成编码（可选：也可在提交时生成）
    generateWorkshopCode()
  } else {
    // 开关关闭：编码必填
    rules.value.workshopCode = [{ required: true, message: "车间编码不能为空", trigger: "blur" }]
  }
})

/** 生成车间编码（规则：WS-YYYYMMDDHHmmss，如WS-20240520143025） */
function generateWorkshopCode() {
  const date = new Date()
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  const second = String(date.getSeconds()).padStart(2, '0')
  const code = `WS-${year}${month}${day}${hour}${minute}${second}`
  form.value.workshopCode = code
}

/** 自动生成开关变化事件 */
function handleCodeSwitchChange() {
  if (autoGenerateCode.value) {
    generateWorkshopCode()
  } else {
    form.value.workshopCode = null  // 关闭时清空手动输入
  }
}
/** 查询车间列表 */
function getList() {
  loading.value = true
  listWorkshop(queryParams.value).then(response => {
    workshopList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    workshopId: null,
    workshopCode: null,
    workshopName: null,
    area: null,
    charge: null,
    enableFlag: null,
    remark: null,
    attr1: null,
    attr2: null,
    attr3: null,
    attr4: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  proxy.resetForm("workshopRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.workshopId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加车间"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _workshopId = row.workshopId || ids.value
  getWorkshop(_workshopId).then(response => {
    form.value = response.data
    autoGenerateCode.value = false  // 修改时禁用自动生成
    open.value = true
    title.value = "修改车间"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["workshopRef"].validate(valid => {
    if (valid) {
         // 提交前检查：如果开关打开且编码为空，重新生成（避免异常情况）
      if (autoGenerateCode.value && !form.value.workshopCode) {
        generateWorkshopCode()
      }
      if (form.value.workshopId != null) {
        updateWorkshop(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addWorkshop(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _workshopIds = row.workshopId || ids.value
  proxy.$modal.confirm('是否确认删除车间编号为"' + _workshopIds + '"的数据项？').then(function() {
    return delWorkshop(_workshopIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('workshop/workshop/export', {
    ...queryParams.value
  }, `workshop_${new Date().getTime()}.xlsx`)
}

getList()
</script>
